package cn.tedu.file;

import java.io.*;
import java.util.Scanner;

/**本类用于IO流文件复制综合案例*/
public class TestCopyFile {
    public static void main(String[] args) {
        System.out.println("请输入源文件的路径");
        Scanner scanner = new Scanner(System.in);
        String f = scanner.nextLine();
        System.out.println("请输入新文件路径");
        String t = scanner.nextLine();

        ZFCopy(f,t);//使用字符流完成复制操作
//        ZJCopy(f,t);//使用字节流完成复制操作
    }

    private static void ZJCopy(String f,String t) {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(new FileOutputStream(t));
            int b;
            while ((b = in.read())!=-1){
                out.write(b);
            }
            System.out.println("复制成功");
        }catch (Exception e){
            System.out.println("失败");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void ZFCopy(String f,String t) {
        BufferedReader in = null;
        BufferedWriter out = null;
        try {
            in = new BufferedReader(new FileReader(f));
            out = new BufferedWriter(new FileWriter(t));
            int b;
            while ((b = in.read())!=-1){
                out.write(b);
            }
            System.out.println("复制成功");
        }catch (Exception e){
            System.out.println("失败");
            e.printStackTrace();
        }finally {
            /**关流是有顺序的，如果有多个流，最后创建的流，最先关闭
             * 多条关流语句需要各自try-catch*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
